var express = require('express');
var router = express.Router();
var mongoose = require("../../mongoose")

//导入连个内置模块
const path = require('path')
const fs = require('fs')
var random = require("../../utils/randomUser") //随机生成name方法

var {
	createUserDate,
	createBirth
} = require('../../utils/createDate')
//创建产品Schema
var schema = new mongoose.Schema({
	imgId: {
		type: String,
		require: true
	}, //图片id
	classId: {
		type: String,
		require: true
	}, //分类id
	url: {
		type: String,
		require: true
	}, //图片地址,
	title: {
		type: String,
		require: true
	}, //图片描述,
	createDate: {
		type: String,
		require: true
	}, //创建时间,
	creatUserPhone: {
		type: String,
		require: true
	}, //创建人手机号,
	creatUserName: {
		type: String,
		require: true
	}, //创建人用户名,
	creatuserImg: {
		type: String,
		require: true
	}, //创建人头像地址,
	giveList: {
		type: Array,
		require: true
	}, //点赞人,
	homeImgAudit: {
		type: Boolean,
		require: true
	}, //是否需要审核,

});
// 定义MongoDB数据模型 (表>=集合)
var homeimg = mongoose.model("homeimgs", schema);

var multer = require("multer");
var upload = multer({
	dest: 'homeImg/'
}) //文件目录


//审核数据集合
var Audit = require('../audit/index');





// 上传到文件地址
router.post('/uploads', upload.single('files'), async function (req, res, next) {
	//重新命名，避免重复
	let imgUrl = await random('xi-img-', 5) + '-' + req.file.originalname
	let oldPath = req.file.path;
	let newPath = 'homeImg/' + imgUrl;
	await fs.renameSync(oldPath, newPath)
	let CObj = {
		code: 200,
		msg: "上传成功",
		success: true,
		imgUrl: '/' + imgUrl
	}
	res.send(CObj)
});

var get_id_string = require('../../utils/setId')

// 上传到数据库
router.post('/create', async function (req, res, next) {
	let body = req.body
	body.createDate = createUserDate()
	body.giveList = []
	const allList = await homeimg.find()
	body.imgId = get_id_string() + allList.length //随机生成id
	let auditlist = await Audit.find() //是否需要审核
	if (auditlist.length != 0) {
		body.homeImgAudit = auditlist[0].homeImgAudit
	} else {
		body.homeImgAudit = false
	}
	homeimg.create(body).then((data) => {
		if (body.homeImgAudit === false) {
			res.send({
				code: 200,
				success: true,
				msg: "上传成功",
				data
			})
		} else {
			res.send({
				code: 204,
				success: true,
				msg: "已上传，管理员已开启审核，正在审核中...",
				data
			})
		}

	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "上传失败"
		})
	});
})

//查询列表信息---已审核过的 展示给前台
router.post('/list', async function (req, res, next) {
	let body = req.body
	if (body.classId == '' || body.classId == undefined || body.classId == null) {
		// 查询已经审核过的数据
		await homeimg.find({
			homeImgAudit: false
		}).sort({
			_id: -1
		}).limit(body.pageSize).skip((body.pageIndex - 1) * body.pageSize).then((data) => {
			res.send({
				code: 200,
				success: true,
				msg: "列表查询成功",
				data,
			})
		}).catch((err) => {
			res.send({
				code: 500,
				success: false,
				msg: "列表查询失败",
				data: err
			})
		});
	} else {
		await homeimg.find({
			classId: body.classId,
			homeImgAudit: false
		}).sort({
			_id: -1
		}).limit(body.pageSize).skip((body.pageIndex - 1) * body.pageSize).then((data) => {
			res.send({
				code: 200,
				success: true,
				msg: "列表查询成功",
				data,
			})
		}).catch((err) => {
			res.send({
				code: 500,
				success: false,
				msg: "列表查询失败",
				data: err
			})
		});
	}



})


//删除多余图片
router.post('/deleteImg', async function (req, res, next) {
	fs.unlinkSync('./homeImg/' + req.body.imageUrl)
	res.send({
		code: 200,
		success: true,
		msg: "多余图片已删除",
	})
})


//用户点赞
router.post('/give', async function (req, res, next) {
	await homeimg.updateOne({
		imgId: req.body.imgId
	}, {
		$push: {
			giveList: req.body.userId
		}
	}).then(data => {
		res.send({
			code: 200,
			msg: "点赞成功",
			success: true,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "点赞失败",
			data: err
		})
	});
})
// 图片搜索
router.post('/searchImg', async function (req, res, next) {
	var title = req.body.title
	const reg = new RegExp(title, 'i')
	var _filter = {}
	if (req.body.classId != '') {
		_filter = {
			$or: [ //多条件，数组
				{
					title: {
						$regex: reg
					}
				},
				{
					creatUserName: {
						$regex: reg
					}
				}
			],
			classId: req.body.classId
		}
	} else {
		_filter = {
			$or: [ //多条件，数组
				{
					title: {
						$regex: reg
					}
				},
				{
					creatUserName: {
						$regex: reg
					}
				}
			]
		}
	}
	await homeimg.find(_filter).sort({
		_id: -1
	}).limit(req.body.pageSize).skip((req.body.pageIndex - 1) * req.body.pageSize).then((data) => {
		res.send({
			code: 200,
			success: true,
			msg: "列表查询成功",
			data,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "列表查询失败",
			data: err
		})
	});
})
// -----------后台管理系统接口-------
// 查询所有
router.post('/admin/list', async function (req, res, next) {
	let body = req.body
	let imgcount = await homeimg.find()
	if (body.classId === '' && body.homeImgAudit === "") {
		// 查询已经审核过的数据
		await homeimg.find().sort({
			_id: -1
		}).limit(body.pageSize).skip((body.pageIndex - 1) * body.pageSize).then((data) => {
			res.send({
				code: 200,
				success: true,
				msg: "列表查询成功",
				data: {
					count: imgcount.length,
					pageSize: body.pageSize,
					pageIndex: body.pageIndex,
					list: data
				},
			})
		}).catch((err) => {
			res.send({
				code: 500,
				success: false,
				msg: "列表查询失败",
				data: err
			})
		});
	} else {

		let params = {}
		if (body.classId !== '' && body.homeImgAudit === "") {
			params.classId = body.classId
		} else if (body.classId === '' && body.homeImgAudit !== "") {
			params.homeImgAudit = body.homeImgAudit
		} else {
			params.homeImgAudit = body.homeImgAudit
			params.classId = body.classId
		}
		await homeimg.find(params).sort({
			_id: -1
		}).limit(body.pageSize).skip((body.pageIndex - 1) * body.pageSize).then((data) => {
			res.send({
				code: 200,
				success: true,
				msg: "列表查询成功",
				data: {
					count: imgcount.length,
					pageSize: body.pageSize,
					pageIndex: body.pageIndex,
					list: data
				},
			})
		}).catch((err) => {
			res.send({
				code: 500,
				success: false,
				msg: "列表查询失败",
				data: err
			})
		});
	}

})

// 获取审核状态
router.get('/admin/getaudit', async function (req, res, next) {
	await Audit.find().then(data => { //是否需要审核
		if (data.length === 0) {
			data = [{
				homeImgAudit: false
			}]
		}
		res.send({
			code: 200,
			msg: "获取成功",
			success: true,
			data,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "获取失败",
			data: err
		})
	});
})
// 开启关闭审核
router.post('/admin/setaudit', async function (req, res, next) {
	let auditlist = await Audit.find() //是否需要审核
	if (auditlist.length === 0) { //如果数据为空就插入一条
		let body = {
			homeImgAudit: req.body.homeImgAudit,
		}
		await Audit.create(body)
	}
	await Audit.updateOne({}, {
		$set: {
			homeImgAudit: req.body.homeImgAudit,
		},
	}).then(data => { //是否需要审核
		res.send({
			code: 200,
			msg: req.body.homeImgAudit ? "已开启审核" : "已关闭审核",
			success: true,
			data,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "已关闭审核",
			data: err
		})
	});
})
// 审核
router.post('/admin/imgsetaudit', async function (req, res, next) {
	await homeimg.updateOne({
		imgId: req.body.imgId
	}, {
		$set: {
			homeImgAudit: req.body.homeImgAudit,
		},
	}).then(data => {
		res.send({
			code: 200,
			msg: req.body.homeImgAudit ? "已修改未通过" : "已修改已通过",
			success: true,
			data,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "审核失败",
			data: err
		})
	});
})

//删除图片
router.post('/admin/deleteImg', async function (req, res, next) {
	await homeimg.deleteOne({
		imgId: req.body.imgId
	}).then(data => {
		fs.unlinkSync('./homeImg/' + req.body.url)
		res.send({
			code: 200,
			msg: "图片已删除",
			success: true,
			data,
		})
	}).catch((err) => {
		res.send({
			code: 500,
			success: false,
			msg: "删除失败",
			data: err
		})
	});
})
module.exports = router;
